package hng.exception;

import hng.util.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
@Slf4j
public class CustomExceptionHandler {

    /**
     * 通过JsonData handle返回业务异常和系统异常给前端，注意反回类型为JSON
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData handle(Exception e) {
        if (e instanceof  BizException) {
            BizException bizException = (BizException) e;
//            log.error("[业务异常{}]", e);
            return JsonData.buildCodeAndMsg(bizException.getCode(), bizException.getMsg());
        } else {
            log.error("[系统异常{}]", e);
            return JsonData.buildError("系统异常，未知的错误，请联系管理员。");
        }
    }

}
